package com.gyh.system.sys.service;


import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gyh.system.common.utils.R;
import com.gyh.system.sys.dao.MenuDao;
import com.gyh.system.sys.dao.RoleDao;
import com.gyh.system.sys.dao.UserDao;
import com.gyh.system.sys.dao.UserTokenDao;
import com.gyh.system.sys.entity.User;
import com.gyh.system.sys.entity.UserToken;
import com.gyh.system.sys.utils.TokenGenerator;

/**
 * 
 * @author 作者 gyh
 * @version 创建时间：2018年7月11日 下午8:32:49
 */
@Service
public class SystemService {

	@Autowired
	private UserDao userDao;
	
	@Autowired
	private MenuDao menuDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private UserTokenDao userTokenDao;
	
	//12小时后过期
  	private final static int EXPIRE = 3600 * 12;
	
	
	public User getUserByUsername(String username) {
		return userDao.getUserByUsername(username);
	}
	
	//密码校验
	public Boolean validatePassword(String plainPassword, String password) {
		return password.equals(plainPassword);
	}
	
	
	
	
	//创建Token
	public R createToken(long userId) {
		//生成一个Token
		String token = TokenGenerator.generatorToken();
		
		//获取当前时间
		Date now = new Date();
		//过期时间
  		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
		
  		//判断是否生成过token
  		UserToken tokenEntity = userTokenDao.get(userId);
		if (tokenEntity == null) {
			tokenEntity = new UserToken();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			userTokenDao.insert(tokenEntity);
		} else {
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			userTokenDao.update(tokenEntity);
		}
		return R.ok().put("token", token).put("expire", EXPIRE);
	}
	
	
}
